package heartbeat;/*

 */

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName MyServer
 * @Author Final
 * @Project DataStructures
 * 心跳机制
 */
public class MyServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

      try {
          ServerBootstrap serverBootstrap = new ServerBootstrap();
          serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                  .handler(new LoggingHandler(LogLevel.INFO))//日志处理器
                  .childHandler(new ChannelInitializer<SocketChannel>() {
                      @Override
                      protected void initChannel(SocketChannel ch) throws Exception {
                          ChannelPipeline pipeline = ch.pipeline();

                          //加入一个netty提供的idlestatehandler
                          /**
                           * idlestatehandler是netty提供的处理空闲状的处理器
                           * long readerIdletime：表示多长时间没有读，就会发送一个心跳检测包检测是否有连接
                           * long writerIdleTime：表示多长时间没有写，就会发送一个心跳检测包检测是否有连接
                           * long allIdleTime：表示多长时间没有读写，就会发送一个心跳检测包检测是否有连接
                           * 当IdlestateEvent触发后，就会传递给管道的下一个handler去处理，通过调用下一个handler的userEventTiggered，在该方法中去处理
                           * IdlestateEvent
                           */
                          pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS))
                          //加入一个空闲检测进行进一步处理的handler（自定义）
                          .addLast(new MyServerHandler());
                      }
                  });
          ChannelFuture sync = serverBootstrap.bind(9000).sync();
          sync.channel().closeFuture().sync();
      }finally {
          bossGroup.shutdownGracefully();
          workerGroup.shutdownGracefully();
      }
    }
}
